package com.example.ecommerce.controller;

import com.example.ecommerce.entity.Order;
import com.example.ecommerce.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/orders")
    public Map<String, Object> createOrder(@RequestBody Map<String, Object> orderData) {
        System.out.println("Received uid: " + orderData.get("uid"));
        Long uid = Long.valueOf(orderData.get("uid").toString());
        String product_name = orderData.get("product_name").toString();
        Integer quantity = Integer.parseInt(orderData.get("quantity").toString());
        String destination_address = orderData.get("destination_address").toString();
        Double total_price = Double.parseDouble(orderData.get("total_price").toString());
        Integer store_id = Integer.parseInt(orderData.get("store_id").toString());

        orderService.createOrder(uid, product_name, quantity, destination_address,total_price,store_id);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "订单创建成功");

        return result;
    }

    @GetMapping("/orders/{uid}")
    public Map<String, Object> getOrdersByUid(@PathVariable Long uid) {

        Map<String, Object> result = new HashMap<>();
        List<Order> orders = orderService.getOrdersByUid(uid);
        result.put("orders", orderService.getOrdersByUid(uid));
        result.put("data", orders);
        result.put("success", true);
        return result;
    }

    @PostMapping("/orders/update")
    public Map<String, Object> updateOrder(@RequestBody Map<String, Object> data) {
        int orderId = Integer.parseInt(data.get("id").toString());
        String newAddress = data.get("destination_address").toString();
        int newQuantity = Integer.parseInt(data.get("quantity").toString());

        boolean success = orderService.updateOrderIfNotShipped(orderId, newAddress, newQuantity);

        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "订单修改成功" : "订单已发货，无法修改");
        return result;
    }


    @DeleteMapping("/orders/{id}/return")
    public Map<String, Object> returnOrder(@PathVariable int id) {
        Map<String, Object> res = new HashMap<>();

        boolean success = orderService.returnOrder(id);

        if (!success) {
            res.put("success", false);
            res.put("message", "订单不存在");
        } else {
            res.put("success", true);
            res.put("message", "订单已退货（删除）");
        }

        return res;
    }

    @GetMapping("/orders/store/{storeId}")
    public Map<String, Object> getOrdersByStore(@PathVariable int storeId) {
        List<Order> orders = orderService.getOrdersByStoreId(storeId);
        Map<String, Object> result = new HashMap<>();
        result.put("orders", orders);
        return result;
    }

    @PostMapping("/orders/update-state")
    public Map<String, Object> updateOrderState(@RequestBody Map<String, Object> data) {
        int orderId = (int) data.get("id");
        String newState = (String) data.get("state");

        boolean success = orderService.updateOrderState(orderId, newState);

        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "状态更新成功" : "更新失败");
        return result;
    }

    @GetMapping("/stats/product-sales")
    public List<Map<String, Object>> getProductSalesStats() {
        return orderService.getProductSalesStats();
    }

    @GetMapping("/stats/seller-sales")
    public List<Map<String, Object>> getSellerSalesStats() {
        return orderService.getSellerSalesStats();
    }

    @GetMapping("/stats/user-spending")
    public List<Map<String, Object>> getUserSpendingStats() {
        return orderService.getUserSpendingStats();
    }


}
